﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.IO;
using System.Net;

namespace Dictionary_offline__tratu.soha.vn_
{
    public partial class frmEngVie2 : DevComponents.DotNetBar.Metro.MetroForm
    {
        public frmEngVie2()
        {
            InitializeComponent();
        }

        public String ListWord = "";
        public string wordIsShowing = "";
        public Font fontDefaut = new Font("Segoe UI", 10, FontStyle.Regular);
        public Font fontSearchWords = new Font("Segoe UI", 11, FontStyle.Regular);
        public Font fontEnglishWords = new Font("Segoe UI", 11, FontStyle.Regular);
        public Font fontPOS = new Font("Segoe UI", 11, FontStyle.Bold);
        public Font fontAcademics = new Font("Segoe UI", 12, FontStyle.Bold);
        public Font fontMeaning = new Font("Segoe UI", 12, FontStyle.Regular);
        public Color colorDefaut = Color.Black;
        public Color colorSearchWords = Color.Red;
        public Color colorExampleWords = Color.Blue;
        public Color colorPOS = Color.Green;
        public Color colorAcademics = Color.OrangeRed;
        public Color colorMeaning = Color.Black;
        public Color colorExampleMeaning = Color.DarkGreen;

        private void cboSearchText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && cboSearchText.Text.TrimEnd() != "")
            {
                btnSearch_Click(null, null);
            }
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (keyData == Keys.Back && cboSearchText.Focused == false)
            {
                cboSearchText.Focus();
            }
            return base.ProcessDialogKey(keyData);
        }

        public void InsertTortbResult2(Color c, Font f, string s)
        {
            rtbResult2.SelectionFont = f;
            rtbResult2.SelectionColor = c;
            rtbResult2.AppendText(s);
        }

        public void MarkKeyWordInExample(string keyWord, string _s)
        {
            string[] _sSlit = _s.TrimEnd().Split(' ');
            InsertTortbResult2(colorExampleWords, fontEnglishWords, "      +");
            foreach (string _subS in _sSlit)
            {
                if (_subS.ToLower() == keyWord.ToLower())
                {
                    InsertTortbResult2(colorSearchWords, fontSearchWords, _subS + " ");
                }
                else
                {
                    InsertTortbResult2(colorExampleWords, fontEnglishWords, _subS + " ");
                }
            }
            rtbResult2.AppendText("\n");
        }

        public Stream GetResult()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://tratu.soha.vn/dict/en_vn/" + cboSearchText.Text.ToLower());
            request.Method = "GET";
            request.ContentLength = 0;
            HttpWebResponse respone = (HttpWebResponse)request.GetResponse();
            return respone.GetResponseStream();
        }


        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                HtmlAgilityPack.HtmlDocument hdocMeaningType = new HtmlAgilityPack.HtmlDocument();
                HtmlAgilityPack.HtmlNodeCollection hdocSubMeaningType;
                HtmlAgilityPack.HtmlNodeCollection hdocSubMeaningExample;
                hdocMeaningType.Load(GetResult(), Encoding.UTF8);
                var result1 = hdocMeaningType.DocumentNode.SelectSingleNode("//h1[@class='firstHeading']/script");
                string tmp = result1.InnerText;
                tmp = tmp.Substring(tmp.IndexOf("=") + 2);
                tmp = tmp.Substring(0, tmp.IndexOf("'")).TrimEnd();
                if (tmp != "Kết quả tìm" && hdocMeaningType.DocumentNode.SelectSingleNode("//div[@class='section-h5']") != null)
                {
                    wordIsShowing = tmp.TrimEnd();
                    txtResult1.Text = tmp;
                    if (!ListWord.Contains(tmp + "#"))
                    {
                        cboSearchText.Items.Add(tmp);
                        ListWord += tmp + "#";
                    }
                    result1 = hdocMeaningType.DocumentNode.SelectSingleNode("//div[@class='section-h5']");
                    txtResult1.Text += "\r\n" + result1.InnerText.TrimStart();
                    rtbResult2.SelectionColor = Color.Black;
                    rtbResult2.Text = "";
                    if (hdocMeaningType.DocumentNode.SelectNodes("//div[@class='section-h2']") != null)
                    {
                        for (int i = 0; i < hdocMeaningType.DocumentNode.SelectNodes("//div[@class='section-h2']").Count; i++)
                        {
                            var item = hdocMeaningType.DocumentNode.SelectNodes("//div[@class='section-h2']")[i];
                            //xuất tên loại từ điển
                            InsertTortbResult2(colorAcademics, fontAcademics, item.SelectSingleNode("descendant::span[@class='mw-headline']").InnerText.TrimEnd() + "\n");
                            //lấy tên từ loại(danh động tính trạng) của từ bằng section 3
                            hdocSubMeaningType = item.SelectNodes("descendant::div[@class='section-h3']");
                            foreach (var subItem1 in hdocSubMeaningType)
                            {
                                //xuất tên từ loại
                                InsertTortbResult2(colorPOS, fontPOS, "  " + subItem1.SelectSingleNode("descendant::span[@class='mw-headline']").InnerText + "\n");
                                //trích xuất nghĩa trong section 5
                                if (subItem1.SelectNodes("descendant::div[@class='section-h5']") != null)
                                {
                                    foreach (var subItem2 in subItem1.SelectNodes("descendant::div[@class='section-h5']"))
                                    {
                                        //Xuất tên nghĩa của từ
                                        InsertTortbResult2(colorMeaning, fontMeaning, "   -" + subItem2.SelectSingleNode("descendant::span[@class='mw-headline']").InnerText + "\n");
                                        //Xuất ví dụ nếu có
                                        if ((hdocSubMeaningExample = subItem2.SelectNodes("descendant::dl/dd/dl/dd")) != null)
                                        {
                                            bool changeEV = true;
                                            foreach (var subItem3 in hdocSubMeaningExample)
                                            {
                                                if (changeEV)
                                                {
                                                    MarkKeyWordInExample(tmp, subItem3.InnerText);
                                                    changeEV = !changeEV;
                                                }
                                                else
                                                {
                                                    InsertTortbResult2(colorExampleMeaning, fontEnglishWords, "       " + subItem3.InnerText);
                                                    changeEV = !changeEV;
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    InsertTortbResult2(colorMeaning, fontMeaning, "   -" + subItem1.SelectSingleNode("descendant::ul").InnerText + "\n");
                                }
                            }
                            rtbResult2.AppendText("\n\r");
                        }
                    }
                    else
                    {
                        hdocSubMeaningType = hdocMeaningType.DocumentNode.SelectNodes("//div[@class='section-h3']");
                        foreach (var subItem1 in hdocSubMeaningType)
                        {
                            //xuất tên từ loại
                            InsertTortbResult2(colorAcademics, fontAcademics, subItem1.SelectSingleNode("descendant::span[@class='mw-headline']").InnerText + "\n");
                            //trích xuất nghĩa trong section 5
                            if (subItem1.SelectNodes("descendant::div[@class='section-h5']") != null)
                            {
                                foreach (var subItem2 in subItem1.SelectNodes("descendant::div[@class='section-h5']"))
                                {
                                    //Xuất tên nghĩa của từ
                                    InsertTortbResult2(colorMeaning, fontMeaning, "   -" + subItem2.SelectSingleNode("descendant::span[@class='mw-headline']").InnerText + "\n");
                                    //Xuất ví dụ nếu có
                                    if ((hdocSubMeaningExample = subItem2.SelectNodes("descendant::dl/dd/dl/dd")) != null)
                                    {
                                        bool changeEV = true;
                                        foreach (var subItem3 in hdocSubMeaningExample)
                                        {
                                            if (changeEV)
                                            {
                                                MarkKeyWordInExample(tmp, subItem3.InnerText);
                                                changeEV = !changeEV;
                                            }
                                            else
                                            {
                                                InsertTortbResult2(colorExampleMeaning, fontEnglishWords, "       " + subItem3.InnerText);
                                                changeEV = !changeEV;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                InsertTortbResult2(colorMeaning, fontMeaning, "   -" + subItem1.SelectSingleNode("descendant::ul").InnerText + "\n");
                            }
                        }
                    }
                }
                else
                {
                    txtResult1.Text = "Not Avalable";
                    rtbResult2.Clear();
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void cboSearchText_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((cboSearchText.Text.ToLower() != wordIsShowing.ToLower()))
            {
                btnSearch_Click(null, null);
            }
        }
    }
}